package kgc.crm.util;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.*;
import kgc.crm.model.User;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
//通过JWT获取Token
@Slf4j
public class JWTManager  {
    //创建token
    public static String creatTokenByClaims(User user) {
        //获取当前的时间戳
        final long millis = System.currentTimeMillis();
        long time = millis+Constant.EXPIR_TIME_HH_6;//存的是毫秒
        JwtBuilder jb = Jwts.builder()
                .setId(user.getUserId()+"")
                .setSubject(user.getUsername()+"")
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256,Constant.SIGN_KEY)
                .setExpiration(new Date(time))   //设置过期时间
                .claim("user", JSON.toJSONString(user));
        final String token = jb.compact();
        log.info("[Token生成] 当前用户ID：{}，身份令牌为：{},",user.getUserId(),token);
        return token;
    }
    //解析token 使用
    private static Claims parseTokenByClaims(String TOKEN) {
        //声明对象
        Claims body = Jwts.parser()
                .setSigningKey(Constant.SIGN_KEY)  //签名所用的key
                .parseClaimsJws(TOKEN).getBody();//解析jws
        return body;
    }

    //获取token之前先验证是否过期
    public static User getUserByToken(String token) {
        //获取user
        try {
            //声明token
            Claims claims = parseTokenByClaims(token);
            return JSON.parseObject(claims.get("user",String.class),User.class);
        } catch (ExpiredJwtException e) {
            log.error("[TOKEN获取] 身份令牌已过期");
            return null;
        }
    }
    //获取用户id
    public static Long getUserIDByToken(String token) {
        try {
            Claims claims = parseTokenByClaims(token);
            return  Long.parseLong(claims.getId());
        } catch (Exception e) {
            log.error("[TOKEN获取] 身份令牌已过期");
            return null;
        }
    }
}
